package mars;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import mars.MarsLaunch;
import mars.mips.hardware.Coprocessor1;
import mars.mips.hardware.Memory;
import mars.mips.hardware.Register;
import mars.mips.hardware.RegisterFile;


/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson (psanderson@otterbein.edu)
and Kenneth Vollmar (kenvollmar@missouristate.edu)

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
/**
 * Portal to Mars
 * 
 * @author Pete Sanderson
 * @version March 2006
 **/
public class Mars {

    public static Float min;
    public static Float max;
    
    public static Float[][] execute_MIPS(String cod, int width, int heigth) {

        Float[][] pixels = new Float[width][heigth];
        
        try {
            File file = new File("MIPS" + System.currentTimeMillis() + ".asm");
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(cod);
            bw.close();

            MarsLaunch m = new mars.MarsLaunch(new String[]{file.getAbsolutePath()});

            int desloc = m.getDataSymbolAddress("pixelsOut");
            ArrayList<Integer> result = m.getMemoryRange("0x" + Integer.toHexString(desloc), "0x" + Integer.toHexString(desloc + 4 * (width * heigth - 1)));

            for (int i = 0; i < result.size(); i++) {

                System.out.println(">> " + Integer.toBinaryString(result.get(i)) + " = " + Float.intBitsToFloat(result.get(i)));

            }

            min = Float.intBitsToFloat(Coprocessor1.getRegister("$f1").getValue());
            max = Float.intBitsToFloat(Coprocessor1.getRegister("$f2").getValue());

            for (int i = 0; i < width; i++) {
                for (int j = 0; j < heigth; j++) {
                    pixels[i][j] = Float.intBitsToFloat(result.get((i * width) + j));
                }
            }


        } catch (IOException ex) {
            Logger.getLogger(Mars.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("Retornando valor...");
        return pixels;
    }

    public static void main(String[] args) throws Exception {
//          Scanner scan = new Scanner(new File("Fibonacci.asm"));
//          String code = "";
//          while(scan.hasNextLine()){
//              code += scan.nextLine() + "\n";
//          }
//
//          execute_MIPS(code);
        int width = 4;
        int height = 4;
//25, 23, 93, 12, | 72, 84, 14, 70, 57, 59, 32, 88, 62, 40, 10, 50




        int[][] pixels = new int[width][height];

        pixels[0][0] = 25;
        pixels[0][1] = 23;
        pixels[0][2] = 93;
        pixels[0][3] = 12;

        pixels[1][0] = 72;
        pixels[1][1] = 84;
        pixels[1][2] = 14;
        pixels[1][3] = 70;

        pixels[2][0] = 57;
        pixels[2][1] = 59;
        pixels[2][2] = 32;
        pixels[2][3] = 88;

        pixels[3][0] = 62;
        pixels[3][1] = 40;
        pixels[3][2] = 10;
        pixels[3][3] = 50;

        float[][][] vectorField = new float[width][height][2];

        //2.0, 1.0, 9.0, 8.0, 7.0, 4.0, 4.0, 2.0,
        vectorField[0][0][0] = 2.0f;
        vectorField[0][0][1] = 1.0f;
        vectorField[0][1][0] = 9.0f;
        vectorField[0][1][1] = 8.0f;
        vectorField[0][2][0] = 7.0f;
        vectorField[0][2][1] = 4.0f;
        vectorField[0][3][0] = 4.0f;
        vectorField[0][3][1] = 2.0f;

        //4.0, 3.0, 2.0, 4.0, 5.0, 7.0, 3.0, 7.0,
        vectorField[1][0][0] = 4.0f;
        vectorField[1][0][1] = 3.0f;
        vectorField[1][1][0] = 2.0f;
        vectorField[1][1][1] = 4.0f;
        vectorField[1][2][0] = 5.0f;
        vectorField[1][2][1] = 7.0f;
        vectorField[1][3][0] = 3.0f;
        vectorField[1][3][1] = 7.0f;

        //9.0, 0.0, 8.0, 6.0, 0.0, 3.0, 5.0, 2.0,
        vectorField[2][0][0] = 9.0f;
        vectorField[2][0][1] = 0.0f;
        vectorField[2][1][0] = 8.0f;
        vectorField[2][1][1] = 6.0f;
        vectorField[2][2][0] = 0.0f;
        vectorField[2][2][1] = 3.0f;
        vectorField[2][3][0] = 5.0f;
        vectorField[2][3][1] = 2.0f;

        //2.0, 8.0, 8.0, 6.0, 5.0, 8.0, 0.0, 5.0
        vectorField[3][0][0] = 2.0f;
        vectorField[3][0][1] = 8.0f;
        vectorField[3][1][0] = 8.0f;
        vectorField[3][1][1] = 6.0f;
        vectorField[3][2][0] = 5.0f;
        vectorField[3][2][1] = 8.0f;
        vectorField[3][3][0] = 0.0f;
        vectorField[3][3][1] = 5.0f;

        width = 10;
        height = 10;

        pixels = new int[width][height];
        vectorField = new float[width][height][2];

        for(int i = 0; i < width; i++){
            for(int j = 0; j < height; j++){
                pixels[i][j] = (int)(Math.random() * 100);
                for(int k = 0; k < 2; k++){
                    vectorField[i][j][k] = (int)(Math.random() * 10);
                }
            }
        }

        System.out.println("Iniciando geração do código...");
        LineIntegralConvolutionMIPS lineIntegralConvolutionMIPS = new LineIntegralConvolutionMIPS(pixels, width, height, vectorField);
        System.out.println("Geração de código finalizada.\n");

        System.out.println("Iniciando execução do código...");
        Float[][] pixelsOut = null;
        pixelsOut = execute_MIPS(lineIntegralConvolutionMIPS.toString(), width, height);
        System.out.println("Execução finalizada.\n");

       
        
        System.out.println("Mostrando resultado...\n");

        System.out.println("\n\n");
        for(int i = 0; i < width; i++){
            for(int j = 0; j < height; j++){
               System.out.printf("%4.4f ", pixelsOut[i][j]);
            }
            System.out.println("");
        }

        System.out.println("");
        System.out.println("################################################");
        System.out.println("################################################");
        System.out.println("################################################");
        System.out.println("");

        System.out.println("Iniciando simulação com código em JAVA...");
        LineIntegralConvolution lineIntegralConvolution = new LineIntegralConvolution(pixels, width, height, vectorField);
        Float[][] r = lineIntegralConvolution.getFlow();
        System.out.println("Finalizado a simulação com código em JAVA.\n");
        System.out.println("Mostrando resultado.\n");

        

        for (int i = 0; i < r.length; i++) {
            for (int j = 0; j < r[i].length; j++) {
                System.out.printf("%4.4f ", r[i][j]);
            }
            System.out.println("");
        }


    }
} 

